package monitor

import (
	"gitee.com/aldrice/monitor/ent/metric"
	"gitee.com/aldrice/monitor/internal/router"
)

type createMetricReq struct {
	Name string `json:"name" validate:"required"`
}

type editMetricReq struct {
	Name     string `json:"name" validate:"required"`
	MetricID int    `json:"metric_id" validate:"required"`
}

func CreateMetric(c *router.Context) error {
	req := new(createMetricReq)
	if err := c.Bind(req); err != nil {
		return err
	}
	if err := c.Validate(req); err != nil {
		return err
	}

	m, err := c.DB().Metric.Create().SetName(req.Name).Save(c.Ctx())
	if err != nil {
		return err
	}

	return c.ApiSuccess(m.ID)
}

func EditMetric(c *router.Context) error {
	req := new(editMetricReq)
	if err := c.Bind(req); err != nil {
		return err
	}
	if err := c.Validate(req); err != nil {
		return err
	}

	_, err := c.DB().Metric.Update().Where(metric.IDEQ(req.MetricID)).
		SetName(req.Name).
		Save(c.Ctx())
	if err != nil {
		return err
	}

	return c.ApiSuccess(nil)
}

// GetMetrics
// @Summary Get all metrics
// @Description 获取所有指标
// @ID monitor-metric-gets
// @Tags metric
// @Accept param
// @Produce json
// @Route /monitor/metrics [get]
func GetMetrics(c *router.Context) error {
	metrics, err := c.DB().Metric.Query().All(c.Ctx())
	if err != nil {
		return err
	}
	return c.ApiSuccess(metrics)
}
